package com.studio5704website.infrastructure.service;

import com.studio5704website.infrastructure.repository.MyBatisUrlPermissionRepository;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 高威
 * redis加载配置
 */
@Configuration
public class RedisLoadConfig {
    private RedisUtil redisUtil;
    private YmlUrlPermission ymlUrlPermission;
    private MyBatisUrlPermissionRepository urlPermissionRepository;
    private String value;

    @Autowired
    public RedisLoadConfig(RedisUtil redisUtil,
                           YmlUrlPermission ymlUrlPermission,
                           MyBatisUrlPermissionRepository urlPermissionRepository,
                           @Value("${spring.profiles.active}") String value) {
        this.redisUtil = redisUtil;
        this.ymlUrlPermission = ymlUrlPermission;
        this.urlPermissionRepository = urlPermissionRepository;
        this.value = value;
        setUrlPermission();
    }

    private void setUrlPermission() {
        switch (value) {
            case "dev":
                redisUtil.flushAll();
                redisUtil.set("urlPermission", ymlUrlPermission.getUrlPermission());
                break;
            case "product":
                redisUtil.set("urlPermission", urlPermissionRepository.getUrlPermission());
                break;
            default:
                redisUtil.set("urlPermission", ymlUrlPermission.getUrlPermission());
                break;
        }
    }

}


@Component
@Data
class YmlUrlPermission {
    Map urlPermission;
    public YmlUrlPermission() {
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("urlPermission.yml"));
        System.out.println(yaml.getObject().toString());
        urlPermission = yaml.getObject();
    }
}
